/**
 * This file is part of Wasagent.
 *
 * Wasagent is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Wasagent is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Wasagent. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package net.wait4it.wasagent.tests;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.management.ObjectName;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.pmi.stat.WSSessionManagementStats;
import com.ibm.websphere.pmi.stat.WSStats;

import net.wait4it.wasagent.jmx.JmxService;
import net.wait4it.wasagent.utils.Result;
import net.wait4it.wasagent.utils.Status;

/**
 * @author Yann Lambret
 *
 */
public class SessionManagerTest extends TestUtils implements Test {

	private static final String message = "application test";
	private static final String query = "WebSphere:type=SessionManager,*";

	// No statistics for WAS internal components
	private static final List<String> exclusions = new ArrayList<String>();

	static {
		exclusions.add("ibmasyncrsp#ibmasyncrsp.war");
	}

	public Result run(AdminClient client, ObjectName perfMbean, String params) {
		Result result = new Result();
		List<String> output = new ArrayList<String>();
		int code = 0;

		/**
		 * Specific test variables
		 */
		Map<String,String> applications = new HashMap<String,String>();
		String[] thresholdsArray;

		/**
		 * Populate the HashMap with application name keys
		 * and string values like 'warning;critical'
		 */
		String[] paramsArray = params.split("\\|");

		for (String app : paramsArray) {
			String[] appArray = (app.split(";", 2));
			applications.put(appArray[0], appArray[1]);
		}

		try {
			Set<ObjectName> mbeans = JmxService.getMbeans(client, query);
			Iterator<ObjectName> iterator = mbeans.iterator();
			while (iterator.hasNext()) {
				WSStats stats = JmxService.getStats(client, perfMbean, iterator.next());
				if (exclusions.contains(stats.getName()))
					continue;
				if (applications.containsKey("*") || applications.containsKey(stats.getName())) {
					long liveCount = getRangeStats(stats, WSSessionManagementStats.LiveCount).getCurrent();
					output.add("app-" + stats.getName().split("#")[0] + "=" + liveCount);

					if (applications.containsKey("*"))
						thresholdsArray = applications.get("*").split(";");
					else
						thresholdsArray = applications.get(stats.getName()).split(";");

					long warning = Long.parseLong(thresholdsArray[0]);
					long critical = Long.parseLong(thresholdsArray[1]);
					code = checkResult(liveCount, critical, warning, code);
				}
				iterator.remove();
			}
		} catch (Exception e) {
			result.setStatus(Status.UNKNOWN);
			result.setMessage(Status.UNKNOWN.getMessage(message));
			return result;
		}

		for (Status status : Status.values()) {
			if (code == status.getCode()) {
				result.setStatus(status);
				result.setMessage(status.getMessage(message));
				Collections.sort(output);
				StringBuilder out = new StringBuilder();
				
				for (String o : output) {
					if (out.length() > 0)
						out.append(" ");
					out.append(o);
				}
				
				result.setOutput(out.toString());
				break;
			}
		}

		return result;
	}

}
